from django.db import models
from django.contrib import admin
from django import forms
from .models import Article, Column, Topic
from django_ckeditor_5.widgets import CKEditor5Widget


# 自定义表单以使用 CKEditor 5 小部件
class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = '__all__'
        widgets = {
            'content': CKEditor5Widget(config_name='default'),
        }

@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    
    # 定义Media类，指定admin自定义CSS文件
    # class Media:
    #     css = {
    #         'all': ('css/ckeditor_custom.css',)
    #     }

    form = ArticleForm  # 使用自定义表单
    list_display = ('title', 'column', 'topics', 'status', 'author', 'publish_date', 'is_recommended', 'redirect_url','update_date', 'keywords')
    list_filter = ('status', 'column', 'is_recommended', 'author')
    search_fields = ('title', 'keywords', 'content')
    list_editable = ('is_recommended', 'status')
    date_hierarchy = 'publish_date'
    ordering = ('-publish_date',)
    formfield_overrides = {
        models.CharField: {'widget': forms.TextInput(attrs={'size': '120'})},
        models.TextField: {'widget': forms.Textarea(attrs={'rows': 10, 'cols': 120})},
        models.ManyToManyField: {'widget': forms.CheckboxSelectMultiple},
    }
    fieldsets = (
        ('基础信息', {
            'fields': ('title', 'column','topics','redirect_url', 'status', 'is_recommended')
        }),
        ('内容信息', {
            'fields': ('content', 'cover_image')
        }),
    )
    save_as = True
    save_on_top = True
    
    def save_model(self, request, obj, form, change):
        if not change:
            obj.author = request.user
        super().save_model(request, obj, form, change)

@admin.register(Column)
class ColumnAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'order')
    prepopulated_fields = {'slug': ('name',)}
    list_editable = ('order',)
    search_fields = ('name', 'slug')
    fields = ('name', 'slug', 'description', 'order')


@admin.register(Topic)
class TopicAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'created_at')
    search_fields = ('name', 'slug')
    prepopulated_fields = {'slug': ('name',)}
    fields = ('name', 'slug', 'description', 'cover_image')
